package cn.fengsweb.tokyotyrant
{
	import flash.utils.ByteArray;

	internal class GetMoreHandler extends AbstractHandler
	{
		private var _getMore:GetMore;
		private var _valueArray:Array;
		private var _currentKey:String;
		
		public function GetMoreHandler(host:String, port:uint)
		{
			super(host, port);
		}
		
		public function connect(getMore:GetMore, ttr:TokyoTyrantResponder) : void
		{
			_ttc		= new TokyoTyrantConnection(_host, _port, false);
			_ttr		= ttr;
			_getMore	= getMore;
			_valueArray	= new Array();
			
			iterateGetOne();
		}
		
		private function iterateGetOne():void
		{
			var key:String			= _getMore.key;
			var sendBytes:ByteArray	= _getMore.sendBytes;
			
			if(null != sendBytes){
				_currentKey	= key;
				defaultHandler(sendBytes, successhandler, failedHandler);
			}else{
				_ttr.result(_valueArray);
				_ttc.close();
			}
		}
		
		private function successhandler(recvBytes:ByteArray):void
		{
			var bytes:ByteArray	= new ByteArray();
			recvBytes.readBytes(bytes);
			
			var keyValueObj:Object	= new Object;
				keyValueObj.key		= _currentKey;
				keyValueObj.value	= Util.bytes2Object(bytes);
			_valueArray.push(keyValueObj);
			
			iterateGetOne();
		}
		
		private function failedHandler():void
		{
			var keyValueObj:Object	= new Object;
				keyValueObj.key		= _currentKey;
				keyValueObj.value	= null;
			_valueArray.push(keyValueObj);
			
			iterateGetOne();
		}
	}
}